/* $RCSFile: LocalizeHelper.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/ADNCRM.Core/Helpers/LocalizeHelper.cs $
 * $log$
 * Revision 6 2010/08/06 19:56:28  christian.surieux
 *   Added Log to All cs files
 */

using System;
using System.Diagnostics;
using System.Globalization;
using System.Web;
using System.Threading;
using System.Resources;
using System.Reflection;
using AddonNice.Diagnostics;
using AddonNice.Configuration;

namespace AddonNice.Helpers
{
	/// <summary>
	/// Help to localize strings
	/// </summary>
	public class LocalizeHelper
	{

        const string strErr1    =   "[E]LocalizeHelper Localize textKey: {0}, The exception thrown if the main assembly does not contain the resources for the neutral culture, and they are required because of a missing appropriate satellite assembly: {1},culture: {2},ex: {2}";
        const string strErr2    =   "[E]LocalizeHelper Localize textKey: {0}, resourceFile: {1},culture: {2},ex: {3}";
        public const string DefaultRessourceItem    =   "ADNCRM";
        public LocalizeHelper()
		{}

        public static string Localize(string textKey)
        {
            return Localize(textKey, textKey);
        }
        
        /// <summary>
        /// Non Breakable Localize: replace all space by non breakable char  &#160;
        /// </summary>
        public static string NoBreakLocalize(string textKey, string translation)
        {
            string str = Localize(textKey, translation);
            if (!string.IsNullOrEmpty(str))
                return str.Trim().Replace(" ", StStr.HTML_SPACE);
            return str;
        }

        /// <summary>
        /// Remove all quote ' or " char to use it inside an javascript string
        /// </summary>
        public static string NoQuoteLocalize(string textKey, string translation)
        {
            string str = Localize(textKey, translation);
            if (!string.IsNullOrEmpty(str))
                return str.Replace("'", StStr.HTML_SPACE).Replace("\"", StStr.HTML_SPACE);
            return str;
        }

        /// <summary>
		/// Returns the translated text corresponding to key textKey, if not found in DefaultRessourceItem, uses the default translation
		/// </summary>
		public static string Localize(string textKey, string translation)
		{
            // Retrieve the value of the string resource named 
            string str      =   string.Empty;
            CultureInfo ci  =   Thread.CurrentThread.CurrentUICulture;
			if (HttpContext.Current != null)
			{
				try
				{
					if ( ResourceTraceSwitch.Sw.TraceVerbose )
                        Trace.WriteLine( string.Format(CultureInfo.InvariantCulture, "[V]LocalizeHelper Localize textKey: {0}", textKey),ResourceTraceSwitch.Sw.Info);
					str     =   (string)HttpContext.GetGlobalResourceObject(DefaultRessourceItem, textKey, ci);
					if ( ResourceTraceSwitch.Sw.TraceVerbose )
                        Trace.WriteLine( string.Format(CultureInfo.InvariantCulture, "[V]LocalizeHelper Localize textKey: {0}= {1}", textKey,str),ResourceTraceSwitch.Sw.Info);
				}
				catch(MissingManifestResourceException mex)
				{
				    if ( ResourceTraceSwitch.Sw.TraceError )
                        Trace.WriteLine( string.Format(strErr1,textKey,DefaultRessourceItem,ci.TwoLetterISOLanguageName,mex),ResourceTraceSwitch.Sw.Info);
			    }
                catch (Exception ex)
                {
                    if ( ResourceTraceSwitch.Sw.TraceError )
                        Trace.WriteLine( string.Format(strErr2, new object[] { textKey, DefaultRessourceItem, ci.TwoLetterISOLanguageName, ex }),ResourceTraceSwitch.Sw.Info);
		        }
			}

            if ( string.IsNullOrEmpty(str) )
                return translation;
            return str;
        }

		/// <summary>
		/// Returns the translated text corresponding to key textKey, uses a special resource category 'resourceFile'
		/// inside DefaultRessourceItem in if not found, uses the default translation
        /// This call is to use when the resx resource file is added in AddonNice global resource assembly DefaultRessourceItem.dll
		/// </summary>
		public static string Localize(string resourceFile,string textKey, string translation)
		{

            // Retrieve the value of the string resource named 
            string str      =   string.Empty;
            string strRes	=   string.Empty;
            CultureInfo ci  =   Thread.CurrentThread.CurrentUICulture;
            try
            {
				if (HttpContext.Current != null)
				{
					if ( ResourceTraceSwitch.Sw.TraceVerbose )
                        Trace.WriteLine( string.Format(CultureInfo.InvariantCulture, "LocalizeHelper Localize resourceFile: {0}, textKey: {1}",resourceFile, textKey),ResourceTraceSwitch.Sw.Info);
					strRes	=	string.Format("{0}|{1}",DefaultRessourceItem,resourceFile);
					str     =   (string)HttpContext.GetGlobalResourceObject(strRes, textKey, ci);
					if ( ResourceTraceSwitch.Sw.TraceVerbose )
                        Trace.WriteLine( string.Format(CultureInfo.InvariantCulture, "LocalizeHelper Localize resourceFile: {0}, textKey: {1} = {2}",strRes, textKey,str),ResourceTraceSwitch.Sw.Info);
				}

            }
			catch(MissingManifestResourceException mex)
			{
				if ( ResourceTraceSwitch.Sw.TraceError )
                    Trace.WriteLine( string.Format(strErr1,textKey,strRes,ci.TwoLetterISOLanguageName,mex),ResourceTraceSwitch.Sw.Info);
			}
            catch (Exception ex)
            {
                if ( ResourceTraceSwitch.Sw.TraceError )
                    Trace.WriteLine( string.Format(strErr2, new object[] { textKey, strRes, ci.TwoLetterISOLanguageName, ex }),ResourceTraceSwitch.Sw.Info);
            }

            if ( string.IsNullOrEmpty(str) )
                return translation;
            return str;
        }

		/// <summary>
		/// Returns the translated text corresponding to key textKey, uses a special resource category 'resourceItm'
		/// inside resourceFile, if not found, uses the default translation
        /// This call is to use when the resx resource file is added as a separate assembly named "resourceFile".dll
		/// </summary>
		public static string Localize(string resourceFile,string resourceItm,string textKey, string translation)
		{

            // Retrieve the value of the string resource named 
            string str      = string.Empty;
            string strRes	= string.Empty;
            CultureInfo ci  = Thread.CurrentThread.CurrentUICulture;
            try
            {
				if (HttpContext.Current != null)
				{
					if ( ResourceTraceSwitch.Sw.TraceVerbose )
                        Trace.WriteLine( string.Format(CultureInfo.InvariantCulture, "[V]LocalizeHelper Localize resourceFile: {0},resourceItem: {1}, textKey: {2}",resourceFile, resourceItm,textKey),ResourceTraceSwitch.Sw.Info);
					strRes	        =	string.Format("{0}|{1}",resourceFile,resourceItm);
					str             = (string)HttpContext.GetGlobalResourceObject(strRes, textKey, ci);
					if ( ResourceTraceSwitch.Sw.TraceVerbose )
                        Trace.WriteLine( string.Format(CultureInfo.InvariantCulture, "[V]LocalizeHelper Localize resourceFile: {0}, textKey: {1} = {2}",strRes, textKey,str),ResourceTraceSwitch.Sw.Info);
				}

            }
			catch(MissingManifestResourceException mex)
			{
				if ( ResourceTraceSwitch.Sw.TraceError )
                    Trace.WriteLine( string.Format(strErr1,textKey,DefaultRessourceItem,ci.TwoLetterISOLanguageName,mex),ResourceTraceSwitch.Sw.Info);
			}
            catch (Exception ex)
            {
                if ( ResourceTraceSwitch.Sw.TraceError )
                    Trace.WriteLine( string.Format(strErr2, new object[] { textKey, strRes, ci.TwoLetterISOLanguageName, ex }),ResourceTraceSwitch.Sw.Info);
            }

            if ( string.IsNullOrEmpty(str) )
                return translation;
            return str;
        }

		/// <summary>
		/// Utility to extract from current thread UICulture the neutral culture name
		/// </summary>
        public static string GetCurrentUINeutralCultureName()
        {
            CultureInfo myCulture = Thread.CurrentThread.CurrentUICulture;
            while (myCulture.Parent != null && myCulture.Parent != CultureInfo.InvariantCulture)
            {
                myCulture = myCulture.Parent;
            }
            return myCulture.TwoLetterISOLanguageName;
        }

        /// <summary>
		/// Utility to extract from current thread Culture the neutral culture name
        /// </summary>
        public static string GetCurrentNeutralCultureName()
        {
            CultureInfo myCulture = Thread.CurrentThread.CurrentCulture;
            while (myCulture.Parent != null && myCulture.Parent != CultureInfo.InvariantCulture)
            {
                myCulture = myCulture.Parent;
            }
            return myCulture.TwoLetterISOLanguageName;
        }

    }
}
